package Hot100.DP;

public class robII {
    public static void main(String[] args) {
        int[] nums = {1,2,1,1};
        System.out.println(new robII().rob(nums));
    }
    //与打家劫舍基础题相比，房屋变成了环，则在计算最后dp[nums.length - 1]时需要额外考虑首尾元素

    public int rob(int[] nums) {
        if (nums.length == 1){
            return nums[0];
        }else if(nums.length == 2){
            return Math.max(nums[0],nums[1]);
        }
        //不考虑尾部元素
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        dp[1] = Math.max(dp[0],nums[1]);
        for (int i = 2; i < dp.length - 1; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i],dp[i - 1]);

        }
        int[] dp2 = new int[nums.length];
        dp2[0] = nums[1];
        dp2[1] = Math.max(dp2[0],nums[2]);
        for (int i = 2; i < dp.length - 1; i++) {
            dp2[i] = Math.max(dp2[i - 2] + nums[i + 1],dp2[i - 1]);
        }

        return Math.max(dp[nums.length - 2] , dp2[nums.length - 2]);

    }
}
